"""
作者: 肖麒
联系方式：QQ：1505448035
时间: 2025/8/6 16:29
文件作用：Curl转Python请求工具
"""

import os
import re
import sys

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QCursor, QIcon
from PyQt6.QtWidgets import (QApplication, QMainWindow, QTextEdit, QPushButton,
                             QVBoxLayout, QHBoxLayout, QWidget, QLabel)


class CurlToPythonConverter(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Curl转Python请求工具-作者QQ：1505448035")
        self.setGeometry(100, 100, 900, 700)

        # 设置窗口图标（确保 111.ico 在当前工作目录下）
        self.setWindowIcon(QIcon(self.get_resource_path('images/favicon.ico')))

        # 设置字体
        font = QFont("Segoe UI", 10)
        self.setFont(font)

        # 创建主部件和布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(15)

        # 添加标题
        title_label = QLabel("Curl命令转Python请求工具")
        title_font = QFont("Segoe UI", 14, QFont.Weight.Bold)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        main_layout.addWidget(title_label)

        # 输入区域
        input_label = QLabel("输入Curl命令:")
        input_label.setStyleSheet("font-weight: bold; margin-bottom: 5px;")
        main_layout.addWidget(input_label)

        self.input_text = QTextEdit()
        self.input_text.setStyleSheet("""
            QTextEdit {
                border: 1px solid #ced4da;
                border-radius: 8px;
                padding: 10px;
                background-color: white;
                selection-background-color: #0078d4;
                selection-color: white;
            }
        """)
        self.input_text.setMinimumHeight(200)
        main_layout.addWidget(self.input_text)

        # 按钮区域
        button_layout = QHBoxLayout()
        button_layout.setSpacing(10)

        self.convert_btn = QPushButton("转换为Python代码")
        self.setup_button_style(self.convert_btn)
        self.convert_btn.clicked.connect(self.convert_curl)
        button_layout.addWidget(self.convert_btn)

        self.clear_btn = QPushButton("清空")
        self.setup_button_style(self.clear_btn)
        self.clear_btn.clicked.connect(self.clear_text)
        button_layout.addWidget(self.clear_btn)

        self.copy_btn = QPushButton("复制结果")
        self.setup_button_style(self.copy_btn)
        self.copy_btn.clicked.connect(self.copy_result)
        button_layout.addWidget(self.copy_btn)

        main_layout.addLayout(button_layout)

        # 输出区域
        output_label = QLabel("Python代码输出:")
        output_label.setStyleSheet("font-weight: bold; margin-bottom: 5px;")
        main_layout.addWidget(output_label)

        self.output_text = QTextEdit()
        self.output_text.setStyleSheet("""
            QTextEdit {
                border: 1px solid #ced4da;
                border-radius: 8px;
                padding: 10px;
                background-color: #f8f9fa;
                selection-background-color: #0078d4;
                selection-color: white;
            }
        """)
        self.output_text.setReadOnly(True)
        self.output_text.setMinimumHeight(200)
        main_layout.addWidget(self.output_text)

        # 状态栏
        self.statusBar().showMessage("就绪")

    def get_resource_path(self, relative_path):
        if hasattr(sys, '_MEIPASS'):
            return os.path.join(sys._MEIPASS, relative_path)
        return os.path.join(os.path.abspath("."), relative_path)

    def setup_button_style(self, button):
        """设置按钮样式，符合Win11风格"""
        button.setStyleSheet("""
            QPushButton {
                background-color: #0078d4;
                color: white;
                border-radius: 4px;
                padding: 8px 16px;
                border: none;
                font-weight: 500;
            }
            QPushButton:hover {
                background-color: #0066cc;
            }
            QPushButton:pressed {
                background-color: #0059b3;
            }
            QPushButton:disabled {
                background-color: #b3d1ff;
                color: #e6f0ff;
            }
        """)
        button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))

    def convert_curl(self):
        """转换curl命令为Python代码"""
        curl_command = self.input_text.toPlainText().strip()
        if not curl_command:
            self.statusBar().showMessage("错误: 请输入Curl命令")
            return

        try:
            # 提取URL
            url_match = re.search(r"curl\s+'([^']+)'", curl_command)
            url = url_match.group(1) if url_match else ""

            # 提取Headers
            headers = {}
            header_matches = re.findall(r"-H\s+'([^:]+):\s*([^']+)'", curl_command)
            for name, value in header_matches:
                headers[name.strip()] = value.strip()

            # 提取Cookies (改进版，兼容大小写)
            cookies = {}
            # 首先检查是否有 -b 参数形式的 cookies
            cookie_match = re.search(r"-b\s+'([^']+)'", curl_command)
            if cookie_match:
                cookie_str = cookie_match.group(1)
                cookie_pairs = cookie_str.split('; ')
                for pair in cookie_pairs:
                    if '=' in pair:
                        key, value = pair.split('=', 1)
                        cookies[key.strip()] = value.strip()
            else:
                # 然后检查 headers 中是否有 cookie 字段（不区分大小写）
                cookie_header_key = None
                for key in headers:
                    if key.lower() == 'cookie':
                        cookie_header_key = key
                        break

                if cookie_header_key:
                    cookie_str = headers[cookie_header_key]
                    # 处理 cookies 字符串，支持 URL 编码的值
                    cookie_pairs = cookie_str.split(';')
                    for pair in cookie_pairs:
                        pair = pair.strip()
                        if '=' in pair:
                            key, value = pair.split('=', 1)
                            cookies[key.strip()] = value.strip()
                    # 从 headers 中移除 cookie 字段，因为已经单独处理
                    del headers[cookie_header_key]

            # 提取Data
            data = {}
            data_match = re.search(r"--data-raw\s+'([^']+)'", curl_command)
            if data_match:
                data_str = data_match.group(1)
                data_pairs = data_str.split('&')
                for pair in data_pairs:
                    if '=' in pair:
                        key, value = pair.split('=', 1)
                        # 处理URL编码
                        try:
                            # 导入URL解码函数unquote，用于将URL编码的字符串转换为原始字符串
                            from urllib.parse import unquote
                            # 对key进行URL解码处理：首先去除首尾空白字符，然后进行URL解码
                            key = unquote(key.strip())
                            # 对value进行URL解码处理：首先去除首尾空白字符，然后进行URL解码
                            value = unquote(value.strip())

                        except:
                            # 如果解码失败，保持原始值
                            key = key.strip()
                            value = value.strip()
                        data[key] = value

            # 生成Python代码
            python_code = "import requests\n\n"

            # 添加Headers
            python_code += "headers = {\n"
            for key, value in headers.items():
                # 跳过Cookie头，因为已经单独处理
                if key.lower() != 'cookie':
                    python_code += f"    '{key}': '{value}',\n"
            python_code += "}\n\n"

            # 添加Cookies
            if cookies:
                python_code += "cookies = {\n"
                for key, value in cookies.items():
                    python_code += f"    '{key}': '{value}',\n"
                python_code += "}\n\n"

            # 添加Data
            if data:
                python_code += "data = {\n"
                for key, value in data.items():
                    python_code += f"    '{key}': '{value}',\n"
                python_code += "}\n\n"

            # 添加请求 (调整参数顺序，将 headers 放在前面)
            method = "get"  # 根据是否有 data 来判断，默认使用 GET
            if data:
                method = "post"
            python_code += f"response = requests.{method}('{url}', "
            python_code += "headers=headers"
            if cookies:
                python_code += ", cookies=cookies"
            if data:
                python_code += ", data=data"
            python_code += ")\n\n"

            # 添加输出语句
            python_code += "print(response)\n"
            python_code += "print(response.text)\n"

            self.output_text.setText(python_code)
            self.statusBar().showMessage("转换成功")
        except Exception as e:
            self.output_text.setText(f"转换失败: {str(e)}")
            self.statusBar().showMessage(f"转换失败: {str(e)}")

    def clear_text(self):
        """清空输入和输出"""
        self.input_text.clear()
        self.output_text.clear()
        self.statusBar().showMessage("已清空")

    def copy_result(self):
        """复制输出结果到剪贴板"""
        result = self.output_text.toPlainText()
        if result:
            clipboard = QApplication.clipboard()
            clipboard.setText(result)
            self.statusBar().showMessage("结果已复制到剪贴板")
        else:
            self.statusBar().showMessage("没有可复制的内容")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    # 设置应用程序样式
    app.setStyle("Fusion")
    window = CurlToPythonConverter()
    window.show()
    sys.exit(app.exec())
